package com.team6.stickynote.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.team6.stickynote.R;
import com.team6.stickynote.beans.StickyNoteBean;

/**
 * Sticky Note 适配器
 */
public class StickyNoteAdapter extends ListAdapter<StickyNoteBean, StickyNoteAdapter.ViewHolder> {

    private OnItemLongClickListener onItemLongClickListener;

    private OnItemClickListener onItemClickListener;

    public StickyNoteAdapter(@NonNull DiffUtil.ItemCallback<StickyNoteBean> diffCallback) {
        super(diffCallback);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView tvTitle;
        private final TextView tvSticky;

        /** 当前选中的 StickyNote */
        private StickyNoteBean selectedStickyNoteBean;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tvTitle);
            tvSticky = itemView.findViewById(R.id.tvSticky);

            itemView.setOnClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(selectedStickyNoteBean.getId());
                }
            });

            itemView.setOnLongClickListener(v -> {
                if (onItemLongClickListener != null) {
                    // 获取当前选中的
                    long id = selectedStickyNoteBean.getId();
                    onItemLongClickListener.onItemLongClick(v, id); // 调用定义的接口的事件函数
                }
                return true;
            });
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 获取自定义的 Sticky 的 View
        View view = View.inflate(parent.getContext(), R.layout.sticky_layout, null);
        // 把 View 发给 holder
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        StickyNoteBean stickyNoteBean = getItem(position);
        holder.selectedStickyNoteBean = stickyNoteBean;
        holder.tvTitle.setText(stickyNoteBean.getTitle());
        holder.tvSticky.setText(stickyNoteBean.getText());
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(long id);
    }

    /**
     * 定义长按事件接口
     */
    public interface OnItemLongClickListener {
        void onItemLongClick(View view, long id);
    }

}
